package com.jsbs.iam.ident.controller;


import com.jsbs.iam.common.core.constant.HttpStatus;
import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.common.core.utils.RequestUtils;
import com.jsbs.iam.ident.auth.SessionInfo;
import com.jsbs.iam.ident.constant.Constants;
import com.jsbs.iam.ident.dto.IdentAdminRoleUserDto;
import com.jsbs.iam.ident.dto.IdentAdminUserRoleVo;
import com.jsbs.iam.ident.dto.IamTokenInfoDto;
import com.jsbs.iam.ident.dto.RequestUserDto;
import com.jsbs.iam.ident.entity.IamAccountBase;
import com.jsbs.iam.ident.entity.IamBlacklistManagement;
import com.jsbs.iam.ident.entity.IamLoginLog;
import com.jsbs.iam.ident.feign.IdentFeignInter;
import com.jsbs.iam.ident.mapper.IamBlacklistManagementMapper;
import com.jsbs.iam.ident.mapper.IdentityMapper;
import com.jsbs.iam.ident.service.ILoginMangerService;
import com.jsbs.iam.ident.service.IamUserLogService;
import com.jsbs.iam.ident.service.SessionService;
import com.jsbs.iam.ident.vo.IamAccountBaseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/iam/ident/sign")
public class SignController extends BaseController{

    @Autowired
    private ILoginMangerService iLoginMangerService;

    @Autowired
    private SessionService sessionService;

    @Autowired
    private IamUserLogService userLogService;

    @Autowired
    private IdentityMapper identityMapper;

    @Autowired
    private IdentFeignInter identFeignInter;

    @Autowired
    private IamBlacklistManagementMapper iamBlacklistManagementMapper;

    /**
     * 功能描述：统一登录接口
     * @param request
     * @param response
     * @param authUser
     * @return
     */
    @PostMapping("/login")
    public Result<SessionInfo> login (HttpServletRequest request, HttpServletResponse response, @RequestBody RequestUserDto authUser){
//        log.info("Route=>SignController method=>login 登录开始参为：{} ", Json.toJsonString(authUser));
        try {
            String account = authUser.getAccount();
            //校验用户是否存在黑名单
            List<IamBlacklistManagement> list = iamBlacklistManagementMapper.getBlacklistManagementAll(account);
            if (CollectionUtils.isNotEmpty(list)) {
                log.info("用户{}在黑名单中",account);
                throw new Exception("此用户在黑名单中，请联系管理员");
            }
            if (StringUtils.isEmpty(account)) {
                throw new Exception("用户名不允许为空");
            }
            String password = authUser.getPassword();
            if (StringUtils.isEmpty(password)) {
                throw new Exception("用户密码不允许为空");
            }

            Result result = iLoginMangerService.login(account,password,request);
            if (result.isSuccess()) {
                // 获取客户端ip
                String ip = RequestUtils.getClientIp(request);
                SessionInfo sessionInfo = (SessionInfo) result.getData();
                String applyUrl = request.getHeader(Constants.APPLY_URL);
                sessionInfo.setIp(ip);
                // 0管理员用户，1普通用户 没有参数默认为普通用户
                String userType = request.getHeader(Constants.X_USER_TYPE);
                List<IdentAdminUserRoleVo> adminUserRoleVoList = null;
                // 普通管理员查询角色列表，超管不用查角色列表
                if (Constants.USER_TYPE_ADMIN.equals(userType) && !sessionInfo.getUserCode().equals(Constants.ADMIN)) {
                    IdentAdminRoleUserDto adminRoleUserDto = new IdentAdminRoleUserDto();
                    adminRoleUserDto.setAccount(sessionInfo.getUserCode());
                    adminUserRoleVoList = identFeignInter.queryAdminRoleByUser(adminRoleUserDto).getData();
                    if (CollectionUtils.isEmpty(adminUserRoleVoList)) {
                        return Result.fail(HttpStatus.FORBIDDEN, "鉴权失败");
                    }
                }
                //创建会话
                sessionService.createSession(request, response, sessionInfo,adminUserRoleVoList,applyUrl,userType);
                //记录登录日志
                IamLoginLog loginLog = new IamLoginLog();
                loginLog.setUserCode(sessionInfo.getUserCode());
                loginLog.setUserName(sessionInfo.getName());
                //登录方式 pc端登录，移动端登录，或者手机号登录，账号登录
//                String mobileDevice = LoginUtil.getRequestHeader(request.getHeader("user-agent"));
                loginLog.setLoginWay(Constants.LOG_LOGIN);
                loginLog.setLoginIp(ip);
                loginLog.setLoginTime(new Date());
                loginLog.setLoginStatus(true);
                loginLog.setIsExceptionLogin(false);
                userLogService.saveIamLoginLog(loginLog);
            } else {
                //记录登录日志
                IamLoginLog loginLog = new IamLoginLog();
                //调用根据用户名查询用户信息的接口 为userCode和userName赋值
//                IamAccountBase accountBase = identityMapper.queryByUserCode(userCode, null);
//                if (accountBase != null) {
//                    loginLog.setUserCode(accountBase.getUserCode());
//                    loginLog.setUserName(accountBase.getName());
//                } else {
//                    //如果登录账号查询不到数据日志记录account
//                    loginLog.setUserCode(account);
//                }
//                loginLog.setUserCode(account);
                //登录方式 pc端登录，移动端登录，或者手机号登录，账号登录
//                String mobileDevice = LoginUtil.getRequestHeader(request.getHeader("user-agent"));
                //登录失败不再通过用户名查找信息 直接塞用户名
                loginLog.setLoginWay(Constants.LOG_LOGIN);
                loginLog.setLoginIp(RequestUtils.getClientIp(request));
                loginLog.setLoginTime(new Date());
                loginLog.setLoginStatus(false);
                loginLog.setIsExceptionLogin(false);
                userLogService.saveIamLoginLog(loginLog);
            }
            return result;
        } catch (Exception e) {
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：统一会话校验接口
     * @param tokenInfo
     * @return
     */
    @PostMapping("/validateSession")
    public Result<SessionInfo> validateSession (@RequestBody IamTokenInfoDto tokenInfo){
        try {
            if (StringUtils.isEmpty(tokenInfo.getToken())) {
                return Result.failWithMsg("token为空");
            }
            // 用于获取应用编码
            if (StringUtils.isEmpty(tokenInfo.getServerName())) {
                return Result.failWithMsg("请求域名为空");
            }
            return sessionService.validateSession(tokenInfo);
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 退出登录接口
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public  Result logout (HttpServletRequest request, HttpServletResponse response) {
        try {
            return iLoginMangerService.logout(request, response);
        } catch (Exception e) {
            return handleException(e);
        }
    }
}
